package com.atguigu.bigdata.spark.core.rdd.operator.transform;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.PairFlatMapFunction;
import scala.Tuple2;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class Spark06_RDD_Operator_Transform_JAVA {
    public static void main(String[] args) {

        // groupBy会将数据源中的每一个数据进行分组判断，根据返回的分组key进行分组
        // 相同的key值的数据会放置在一个组中

        SparkConf conf = new SparkConf().setMaster("local[*]").setAppName("sparkCore");
        JavaSparkContext sc = new JavaSparkContext(conf);

        List<Integer> list = Arrays.asList(1,2,3,4);
        
        JavaRDD<Integer> rdd =  sc.parallelize(list,2);

        JavaPairRDD<Integer, Iterable<Integer>> groupby = rdd.groupBy(new Function<Integer, Integer>() {
            //相同结果的合在一个分区里
            @Override
            public Integer call(Integer integer) throws Exception {
                return integer % 2;
            }
        }, 2);

        List<Tuple2<Integer, Iterable<Integer>>> res = groupby.collect();
        for(Tuple2 val : res) {
            System.out.println(val.toString());
        }

        sc.stop();


    }
}
